package cn.tedu.ivos.user.service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.dto.UserLoginParam;
import cn.tedu.ivos.user.pojo.dto.UserQuery;
import cn.tedu.ivos.user.pojo.dto.UserSaveParam;
import cn.tedu.ivos.user.pojo.entity.User;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import cn.tedu.ivos.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public UserVO login(UserLoginParam userLoginParam) {
        log.debug("用户登录业务参数：{}", userLoginParam);
        UserVO userVO = userMapper.selectByUsername(userLoginParam.getUsername());
        if (userVO == null) {
            //如果主业务遇到了问题，需要抛出业务层异常，此时的异常结果由全局异常处理器返回给前端
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }
        if (!userVO.getPassword().equals(userLoginParam.getPassword())) {
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }
        //只有不出现上方的两个异常情况，才会执行下面的代码，将业务层结果交给controller返回给前端
        log.debug("用户查询结果:{}", userVO);
        return userVO;
    }

    @Override
    public void saveUser(UserSaveParam userSaveParam) {
        log.debug("保存用户业务参数：{}", userSaveParam);
        User user = new User();
        BeanUtils.copyProperties(userSaveParam, user);
        user.setCreateTime(new Date());
        user.setPassword("123456");
        userMapper.insert(user);
    }

    @Override
    public List<UserVO> selectUser(UserQuery userQuery) {
        log.debug("查询用户业务参数：{}", userQuery);
        List<UserVO> list = userMapper.selectUser(userQuery);
        return list;
    }

    @Override
    public List<UserVO> selectAuditList(Long parentId) {
        log.debug("查询审批人业务列表：parentId = {}", parentId);
        //1.准备一个空集合，用来保存查出来的多个审批人
        ArrayList<UserVO> userVOList = new ArrayList<>();
        //2.先根据传过来的直属领导id查出直属领导
        UserVO auditUser1 = userMapper.selectById(parentId);
        userVOList.add(auditUser1);
        //3.如果有直属领导，且直属领导还有上级
        if (auditUser1 != null && auditUser1.getParentId() != null) {
            //4.再根据直属领导的领导id将上上级查出来
            UserVO auditUser2 = userMapper.selectById(auditUser1.getParentId());
            userVOList.add(auditUser2);
        }
        //5.将准备好的审批人列表返回给上一层
        return userVOList;
    }
}